// detail/userpage/userpage.js
Page({

  //页面的初始数据
  data: {

  },

 //选择图片
 choosebg: function() {
  wx.showActionSheet({
    itemList: ["拍照", "从相册中选择"],
    itemColor: "#CED63A",
    success: (res)=> {
      if(!res.cancel) {
        if(res.tapIndex == 0) {
          this.imgWShow("camera")        //拍照
        } else if (res.tapIndex == 1) {
          this.imgWShow("album")      //相册
        }
      }
    }
  })

},

// 点击调用手机相册/拍照
imgWShow: function(type) {
  let len = 0;
  if(this.data.imgList != null) {
    len = this.data.imgList.length
  }   

  //获取当前已有的图片
  wx.chooseImage({
    count: 1,    
    sizeType: ['original', 'compressed'],        //可以指定是原图还是压缩图,默认二者都有
    sourceType: [type],             //可以指定来源是相册还是相机, 默认二者都有
    success: (res)=> {
      wx.showToast({
        title: '正在上传...',
        icon: "loading",
        mask: true,
        duration: 1000
      })
      this.setData({
        imagePath:res.tempFilePaths[0]
      })
       //上传图片打印文本
       wx.uploadFile({
        filePath: res.tempFilePaths[0],
        name: 'image',
        header: {
          'content-type': 'multipart/form-data'
        },
        url: 'https://www.prebeauty.work:3001/api/upload',
        success:res=>{
          console.log(res.data);
          this.setData({
            userbgimg: 'https://www.prebeauty.work:3001/static/image/'+ res.data
          })

          var id = this.data.id
          var bgimg =  this.data.userbgimg
          //图片上传成功后put请求
          wx.request({
            url: `https://www.prebeauty.work:3001/api/userpage/${id}`,
            data:{
              userbgimg:bgimg
            },
            header:{
              'content-type':'application/json'
            },
            method:'PUT',
            success:res=>{
              wx.setStorageSync('userbgimg', this.data.userbgimg)
              wx.showToast({
                title: '图片更改成功,请进行刷新',
                icon: 'none'
              })
            },
          })
        }
      })
    },
    fail: function () {
      wx.showToast({
        title: '图片上传失败',
        icon: 'none'
      })
      return;
    }
    
  })
},

//点赞
like:function(e){
  //获取所点动态信息
  let sayid=e.currentTarget.dataset.id
  let like =e.currentTarget.dataset.like
  let img  =e.currentTarget.dataset.img
  let num  =e.currentTarget.dataset.num
  let likeid=e.currentTarget.dataset.likeid

  console.log(sayid,like,img,num)
  if(like=="true"){ //取消点赞     
    like="false"
    --num
    img="/icon/like.png"
  }else{ //点赞
    like="true"
    ++num
    img="/icon/like1.png"
  }

  //更改当前动态点赞数量信息
  wx.request({
    url: `https://www.prebeauty.work:3001/api/says/${sayid}`,
    data:{
      likenum:num
    },
    header: {
      'content-type': 'application/json'
    },
    method: 'PUT',
    success:(res)=>{

    }
  })
  //更改当前动态用户点赞信息
  wx.request({
    url: `https://www.prebeauty.work:3001/api/like/${likeid}`,
    data:{
      sayid:sayid,
      userid:this.data.id,
      islike:like,
      likeimg:img
    },
    header: {
      'content-type': 'application/json'
    },
    method: 'PUT',
    success:(res)=>{

      //更改本地 当前动态点赞信息
      let saysdata=this.data.sayslist
      for(let i=0;i<saysdata.length;i++){
        if(saysdata[i].sayid==sayid){
          saysdata[i].islike=like
          saysdata[i].likenum=num
          saysdata[i].likeimg=img
          this.setData({
            sayslist:saysdata
          })
        }
      }
    }
  })
   
},
  
  //onload 生命周期函数--监听页面加载
  onLoad: function (options) {
    this.setData({
      id: wx.getStorageSync('userid'),
      img:wx.getStorageSync('userimg'),
      name:wx.getStorageSync('username'),
    })
    this.setData({
      userid:options.userid
    })
    const that=this

    //获取用户信息
    wx.request({
      url: `https://www.prebeauty.work:3001/api/userpage?userid=${this.data.userid}`,
      header: {
        'content-type': 'application/json'
      },
      method: 'GET',
      success:(res)=>{
        console.log(res.data[0])
        that.setData({
          userlist:res.data[0]
        });     
        
        //获取用户动态信息
        wx.request({
          url: `https://www.prebeauty.work:3001/api/says?userid=${this.data.userid}`,
          header: {
            'content-type': 'application/json'
          },
          method: 'GET',
          success:async (res)=>{
            console.log(res.data)
            const says=res.data

            //时间
            for(let i=0;i<says.length;i++){
              // let time1=says[i].saytime.slice(0,10)
              // let time2=says[i].saytime.slice(14,19)
              // says[i].saytime=time1+' '+time2

              //图片 字符串->数组
              if(says[i].sayimg){
                let sayimgs=says[i].sayimg.slice(1,-1)
                sayimgs=sayimgs.split(',')
                for(let j=0;j<sayimgs.length;j++){
                  sayimgs[j]=sayimgs[j].slice(1,-1)
                  sayimgs[j]="https://www.prebeauty.work:3001/static/image/"+sayimgs[j]
                }
                says[i].sayimg=sayimgs
              }    

              //判断是否点赞 初始点赞数
              await new Promise((rv,rj)=>{
                wx.request({
                  url: `https://www.prebeauty.work:3001/api/like?userid=${this.data.id}&sayid=${says[i].sayid}`,
                  header: {
                    'content-type': 'application/json'
                  },
                  method: 'GET',
                  success:(res)=>{
                    console.log(this.data.id,says[i].sayid)
                    console.log(res.data)
                    says[i].likeid=res.data[0].id
                    says[i].islike=res.data[0].islike
                    says[i].likeimg=res.data[0].likeimg
                    rv()
                  },
                  fail : err => {
                    rv()
                  }
                })
              })
              
            }
            that.setData({
              sayslist:says
            });
          }
        })
      }
    })
  },

  //生命周期函数--监听页面初次渲染完成
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //验证用户登录
    if(!wx.getStorageSync('token')){
      wx.showModal({
        title: '用户未登录',
        content: '请先进行授权登录',
        success(res) {
          if (res.confirm) {
            console.log('确定')
            wx.switchTab({
              url: '/pages/home/home'
           })
          } else if (res.cancel) {
            console.log('取消')
            wx.switchTab({
              url: '/pages/index/index'
           })
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      id: wx.getStorageSync('userid'),
      img:wx.getStorageSync('userimg'),
      name:wx.getStorageSync('username'),
    })
    const that=this

    //获取用户信息
    wx.request({
      url: `https://www.prebeauty.work:3001/api/userpage?userid=${this.data.userid}`,
      header: {
        'content-type': 'application/json'
      },
      method: 'GET',
      success:(res)=>{
        console.log(res.data[0])
        that.setData({
          userlist:res.data[0]
        });     
        
        //获取用户动态信息
        wx.request({
          url: `https://www.prebeauty.work:3001/api/says?userid=${this.data.userid}`,
          header: {
            'content-type': 'application/json'
          },
          method: 'GET',
          success:async (res)=>{
            console.log(res.data)
            const says=res.data

            //时间
            for(let i=0;i<says.length;i++){
              // let time1=says[i].saytime.slice(0,10)
              // let time2=says[i].saytime.slice(14,19)
              // says[i].saytime=time1+' '+time2

              //图片 字符串->数组
              if(says[i].sayimg){
                let sayimgs=says[i].sayimg.slice(1,-1)
                sayimgs=sayimgs.split(',')
                for(let j=0;j<sayimgs.length;j++){
                  sayimgs[j]=sayimgs[j].slice(1,-1)
                  sayimgs[j]="https://www.prebeauty.work:3001/static/image/"+sayimgs[j]
                }
                says[i].sayimg=sayimgs
              }    

              //判断是否点赞 初始点赞数
              await new Promise((rv,rj)=>{
                wx.request({
                  url: `https://www.prebeauty.work:3001/api/like?userid=${this.data.id}&sayid=${says[i].sayid}`,
                  header: {
                    'content-type': 'application/json'
                  },
                  method: 'GET',
                  success:(res)=>{
                    console.log(this.data.id,says[i].sayid)
                    console.log(res.data)
                    says[i].likeid=res.data[0].id
                    says[i].islike=res.data[0].islike
                    says[i].likeimg=res.data[0].likeimg
                    rv()
                  },
                  fail : err => {
                    rv()
                  }
                })
              })
              
            }
            that.setData({
              sayslist:says
            });
          }
        })
      }
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})